package demo.thread;

public class Demo3 {
    private static boolean flag = true;

    public static void main1(String[] args) throws InterruptedException {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    System.out.println("t线程执行中 " + System.currentTimeMillis());
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("t线程执行结束 " + System.currentTimeMillis());
                }
            }
        });
        t.start();
        Thread.sleep(100);
        flag = false;
        System.out.println("主线程通知 t线程 执行结束" + System.currentTimeMillis());
    }

    public static void main2(String[] args) throws InterruptedException {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println("线程执行中 i = " + i);
                }
            }
        });
        t.start();
        System.out.println("开始等待");
        t.join();
        System.out.println("等待结束");
    }

    public static void main(String[] args) throws InterruptedException {
        Object object = new Object();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (object) {
                    for (int i = 0; i < 5; i++) {
                        System.out.println("线程执行中 i = " + i);
                    }
                    object.notify();
                }
            }
        });
        t.start();
        System.out.println("开始等待");
        synchronized (object) {
            object.wait();
        }
        System.out.println("等待结束");
    }
}
//    public static void main(String[] args) throws InterruptedException {
//        boolean flag = true;
//        Thread t = new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while (flag){
//                    System.out.println("线程执行中 ");
//                }
//            }
//        });
//        Thread.sleep(100);
//        flag = false;
//    }

